/*************************************************************************
	> File Name: comm.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/09/12 14:13
 ************************************************************************/

#ifndef _COMM_H
#define _COMM_H

#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <fcntl.h>
#include <cassert>
#include <sys/shm.h>
#include "Log.hpp"

#define PATH_NAME "."
#define PROJ_ID 0x66
#define SHM_SIZE 4096
#define BUFFER_SIZE 32
#define FIFO_NAME "./fifo.ipc"

#define READ O_RDONLY
#define WRITE O_WRONLY

class Init
{
public:
    Init ()
    {
        umask(0);
        int n = mkfifo(FIFO_NAME, 0666);
        assert(n == 0);
        (void)n;
        Log("Create fifo success", Notice) << std::endl;
    }
    ~Init ()
    {
        unlink(FIFO_NAME);
        Log("Remove fifo success", Notice) << std::endl;
    }
};

int OpenFIFO(std::string pathname, int flags)
{
    int fd = open(pathname.c_str(), flags);
    assert(fd >= 0);
    return fd;
}

void Wait(int fd)
{
    Log("Waiting...", Notice) << std::endl;
    uint32_t temp = 0;
    ssize_t s = read(fd, &temp, sizeof(uint32_t));
    assert(s == sizeof(uint32_t));
    (void)s;
}

void Signal(int fd)
{
    uint32_t temp = 1;
    ssize_t s = write(fd, &temp, sizeof(uint32_t));
    assert(s == sizeof(uint32_t));
    (void)s;
    Log("Awaking...", Notice) << std::endl;
}

void CloseFifo(int fd)
{
    close(fd);
}

#endif
